﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using RearLivestock.Common.Domains.Enum;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using System.Diagnostics;

namespace RearLivestock.Beginning.Api.Application.Command.Farrowing
{
    public class QueryFarrowingsHandler : IRequestHandler<QueryFarrowingsCommand, Result<PageResultDto<FarrowingsDto>>>
    {
        /// <summary>
        /// 母猪分娩仓储
        /// </summary>
        private readonly IBaseRepository<Farrowings> farrowingsRepository;
        /// <summary>
        /// 基本信息耳号仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationRepository;
        /// <summary>
        /// 栋舍信息仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;
        /// <summary>
        ///  栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> fieldsRepository;
        /// <summary>
        /// 批次仓储
        /// </summary>
        private readonly IBaseRepository<Batchs> batchsRepository;
        /// <summary>
        /// 分娩难易
        /// </summary>
        private readonly IBaseRepository<Difficulties> difficultiesRepository;
        /// <summary>
        /// 母性
        /// </summary>
        private readonly IBaseRepository<Maternals> maternalsRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="farrowingsRepository"></param>
        /// <param name="basicInformationRepository"></param>
        /// <param name="bedroomsRepository"></param>
        /// <param name="batchsRepository"></param>
        /// <param name="difficultiesRepository"></param>
        /// <param name="maternalsRepository"></param>
        public QueryFarrowingsHandler(IBaseRepository<Farrowings> farrowingsRepository, IBaseRepository<BasicInformation> basicInformationRepository, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<Fields> fieldsRepository, IBaseRepository<Batchs> batchsRepository, IBaseRepository<Difficulties> difficultiesRepository, IBaseRepository<Maternals> maternalsRepository)
        {
            this.farrowingsRepository = farrowingsRepository;
            this.basicInformationRepository = basicInformationRepository;
            this.bedroomsRepository = bedroomsRepository;
            this.fieldsRepository = fieldsRepository;
            this.batchsRepository = batchsRepository;
            this.difficultiesRepository = difficultiesRepository;
            this.maternalsRepository = maternalsRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<FarrowingsDto>>> Handle(QueryFarrowingsCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<FarrowingsDto>>() { Code = (int)CommonErrorCode.Search, Data = new PageResultDto<FarrowingsDto>() };
            var page = new PageResultDto<FarrowingsDto>() { TotalCount = 0, PageCount = 0, List = new List<FarrowingsDto>() };
            try
            {
                var list = await (from a in await farrowingsRepository.GetAll()
                                  join b in await basicInformationRepository.GetAll()
                                  on a.BasicInforId equals b.BasicInforId
                                  join c in await bedroomsRepository.GetAll()
                                  on a.BedroomId equals c.BedroomId
                                  join d in await batchsRepository.GetAll()
                                  on a.BatchId equals d.BatchId
                                  join e in await difficultiesRepository.GetAll()
                                  on a.DifficultieId equals e.DifficultieId
                                  join f in await maternalsRepository.GetAll()
                                  on a.MaternalId equals f.MaternalId
                                  join g in await fieldsRepository.GetAll()
                                  on a.FieldId equals g.FieldId
                                  where a.IsFarrowings == 0
                                  select new FarrowingsDto()
                                  {
                                      FarrowingId = a.FarrowingId,
                                      BasicInforId = a.BasicInforId,
                                      FarrowingDate = a.FarrowingDate,
                                      GestationNum = a.GestationNum,
                                      DifficultieId = a.DifficultieId,
                                      BatchId = a.BatchId,
                                      MaternalId = a.MaternalId,
                                      Lactation = a.Lactation,
                                      Mastitis = a.Mastitis,
                                      NestNumber = a.NestNumber,
                                      LivePigNum = a.LivePigNum,
                                      NestWeight = a.NestWeight,
                                      Gender = b.Gender,
                                      BedroomId = a.BedroomId,
                                      FieldId = a.FieldId,
                                      TurnBuilding = a.TurnBuilding,
                                      TurnColumn = a.TurnColumn,
                                      IsFarrowings = a.IsFarrowings,
                                      EarNumber = b.EarNumber,
                                      Electronicearlabel = b.Electronicearlabel,
                                      BedroomName = c.BedroomName,
                                      PersonName = c.PersonName,
                                      BatchName = d.BatchName,
                                      DifficultieName = e.DifficultieName,
                                      MaternalName = f.MaternalName,
                                      FieldName = g.FieldName,
                                  }).ToListAsync();
                //if (request.KaiDate != null)
                //{
                //    list = list.Where(d => d.FarrowingDate >= request.KaiDate).ToList();
                //}
                //if (request.EndDate != null)
                //{
                //    list = list.Where(d => d.FarrowingDate <= request.EndDate).ToList();
                //}
                if (request.BasicInforId != 0)
                {
                    list = list.Where(d => d.BasicInforId == request.BasicInforId).ToList();
                }
                if (request.BedroomId != 0)
                {
                    list = list.Where(d => d.BedroomId == request.BedroomId).ToList();
                }
                if (!string.IsNullOrEmpty(request.TurnBuilding))
                {
                    list = list.Where(d => d.TurnBuilding.Contains(request.TurnBuilding)).ToList();
                }
                if (!string.IsNullOrEmpty(request.NestNumber))
                {
                    list = list.Where(d => d.NestNumber.Contains(request.NestNumber)).ToList();
                }
                //总条数
                page.TotalCount = list.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.pageSize);
                page.List = list.OrderBy(d => d.FarrowingId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = page;
                result.Code = (int)CommonErrorCode.Success;
                result.Msg = "母猪分娩列表显示成功";
            }
            catch (Exception)
            {
                result.Msg = "母猪分娩列表显示异常";
            }
            return result;
        }

    }
}
